#!/bin/bash
#功能：umask，添加/etc/profile

USER_MASK=027
SRC_FILE=/etc/profile
###################################################################################
#SH
SHPATH=`readlink -f $0`
SHDIR=`dirname $SHPATH`
SHNAME="$0"

#DIR
LOG_DIR=$SHDIR/logs/$SHNAME
TMP_DIR=$SHDIR/temp/$SHNAME
mkdir -p $LOG_DIR $TMP_DIR

#
if [ ! -f $SRC_FILE.init.bak ];then cp $SRC_FILE $SRC_FILE.init.bak;fi


LINE_VAR=`cat $SRC_FILE|grep -v ^#|awk  '$1=="umask" {print}'`
if [ -z "$LINE_VAR" ];then 
	echo "umask $USER_MASK" >> $SRC_FILE
	if [ $? -eq 0 ];then echo "Success,FILE=$SRC_FILE 添加策略:umask $USER_MASK 成功。";else echo "Error!FILE=$SRC_FILE  添加策略:umask $USER_MASK 失败！请检测文件权限，或使用root用户重试！";fi
else
	LINE_VAR_NUM=`cat -n $SRC_FILE|awk '{print $0,$1}'|awk '{$1=null;print}'|grep -v ^#|awk  '$1=="umask" {print}'|awk '{print $NF}'`
	for i in `echo $LINE_VAR_NUM`
	do
		UMASK_TEST="`sed -n ${i}p $SRC_FILE |grep -v ^#|awk  '$1=="umask" {print}'|awk -v var2=$USER_MASK '$2==var2 {print}'`"
		if [ ! -z "$UMASK_TEST" ];then  UMASK_SUM="$UMASK_SUM $i";fi
	done
	WC_W=`echo $UMASK_SUM|wc -w`
	if [ $WC_W -eq 0 ];then
		for ii in `echo $LINE_VAR_NUM|xargs -n1`
		do
		II_I=$((ii-2))
		II_A=$((ii+2))
		sed -n "${II_I},${II_A}"p $SRC_FILE|grep -iE "if|else" >/dev/null
		if [ ! $? -eq 0 ];then	sed -i  "$ii s/^/#/" $SRC_FILE ;else sed -i "${ii}c    umask 027" $SRC_FILE;fi
		done
		echo "umask $USER_MASK" >> $SRC_FILE
		if [ $? -eq 0 ];then echo "Success,FILE=$SRC_FILE 添加策略:umask $USER_MASK 成功。";else echo "Error!FILE=$SRC_FILE  添加策略:umask $USER_MASK 失败！请检测文件权限，或使用root用户重试！";fi
	else 
		UMASK_NUM=`echo $UMASK_SUM|xargs -n1|tail -n1`
		for ii in `echo $LINE_VAR_NUM|xargs -n1|grep -v $UMASK_NUM`
		do
		II_I=$((ii-2))
		II_A=$((ii+2))
		sed -n "${II_I},${II_A}"p $SRC_FILE|grep -iE "if|else" >/dev/null
		if [ ! $? -eq 0 ];then	sed -i  "$ii s/^/#/" $SRC_FILE ;else sed -i "${ii}c    umask 027" $SRC_FILE;fi
		 
		done
		echo "TIP,FILE=$SRC_FILE 已存在策略:umask $USER_MASK 跳过操作。"
	fi

fi
source $SRC_FILE

